﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace Workflows.Components.TextMining.EnumerationObjects
{
    public partial class ExtractionTester : Form
    {
        public ExtractionTester()
        {
            InitializeComponent();
        }

        private void ExtractionTester_Load(object sender, EventArgs e)
        {
            this.PopulateDefaultExtractionRules();
        }

        private void btn_BrowseTestFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                this.txt_TestFilePath.Text = dlg.FileName;
            }
        }

        private void btn_Test_Click(object sender, EventArgs e)
        {
            ExtractionRule rule=this.SaveExtractionRules();
            this.dv_Result.DataSource = null;

            try
            {
                ExtractionWorker2 worker = new ExtractionWorker2();
                Dictionary<int, DataTable> recordsByPages = worker.TestTableDataExtraction(this.txt_TestFilePath.Text);
                DataTable dtOutput = new DataTable();
                if(recordsByPages !=null && recordsByPages.Count>0)
                {
                    foreach(DataTable dtData in recordsByPages.Values)
                    {
                        foreach(DataColumn col in dtData.Columns)
                        {
                            if(!dtOutput.Columns.Contains(col.ColumnName))
                            {
                                dtOutput.Columns.Add(col.ColumnName, typeof (string));
                            }
                        }
                    }
                }
                
                dtOutput.Columns.Add("PageNumber", typeof(int));
                if (recordsByPages.Count > 0)
                {
                    foreach (int pageNum in recordsByPages.Keys)
                    {
                        DataTable dtData = recordsByPages[pageNum];
                        foreach (DataRow dr in dtData.Rows)
                        {
                            DataRow drNew = dtOutput.NewRow();
                            foreach (DataColumn col in dtData.Columns)
                            {
                                drNew[col.ColumnName] = dr[col.ColumnName];
                            }
                            drNew["PageNumber"] = pageNum;
                            dtOutput.Rows.Add(drNew);
                        }
                    }
                }
                this.dv_Result.DataSource = dtOutput;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        #region extraction rules
        private void PopulateDefaultExtractionRules()
        {
            ExtractionRule rule = ExtractionRule.ReadRuleFromXmlFile();
            this.txt_Header.Text = rule.TableHeader;
            this.txt_Footer.Text = rule.TableFooter;
            this.dv_FieldMappings.Rows.Clear();

            Dictionary<string, DataGridViewRow> allFields = new Dictionary<string, DataGridViewRow>();
            int optionIndex = 0;
            int optionCount = rule.ColHeaderOptions.Count;
            foreach (int applyOrder in rule.ColHeaderOptions.Keys)
            {
                optionIndex += 1;
                List<PdfTableColumnHeaderMapping> colMappings = rule.ColHeaderOptions[applyOrder];
                foreach (PdfTableColumnHeaderMapping colMapping in colMappings)
                {
                    if (!allFields.ContainsKey(colMapping.FieldNameInDB.ToUpper()))
                    {
                        DataGridViewRow dr = new DataGridViewRow();
                        DataGridViewTextBoxCell cellColNameInDB = new DataGridViewTextBoxCell();
                        cellColNameInDB.Value = colMapping.FieldNameInDB;
                        dr.Cells.Add(cellColNameInDB);
                        for (int i = 0; i < optionCount; i++)
                        {
                            DataGridViewTextBoxCell cellOption = new DataGridViewTextBoxCell();
                            cellOption.Value = string.Empty;
                            dr.Cells.Add(cellOption);
                        }
                        dr.Cells[optionIndex].Value = colMapping.FieldNameInPdf;
                        allFields.Add(colMapping.FieldNameInDB.ToUpper(), dr);
                    }
                    else
                    {
                        DataGridViewRow dr = allFields[colMapping.FieldNameInDB.ToUpper()];
                        dr.Cells[optionIndex].Value = colMapping.FieldNameInPdf;
                    }
                }
            }
            foreach (string fieldNameInDB in allFields.Keys)
            {
                this.dv_FieldMappings.Rows.Add(allFields[fieldNameInDB]);
            }
        }

        private ExtractionRule SaveExtractionRules()
        {
            ExtractionRule rule = new ExtractionRule();
            rule.TableHeader = this.txt_Header.Text;
            rule.TableFooter = this.txt_Footer.Text;
            Dictionary<int, List<PdfTableColumnHeaderMapping>> colOptions = new Dictionary<int, List<PdfTableColumnHeaderMapping>>();
            for (int colIndex = 1; colIndex < this.dv_FieldMappings.Columns.Count; colIndex++)
            {
                List<PdfTableColumnHeaderMapping> colMappings = new List<PdfTableColumnHeaderMapping>();
                foreach (DataGridViewRow dr in this.dv_FieldMappings.Rows)
                {
                    if (!dr.IsNewRow && dr.Cells[0].Value != null && dr.Cells[colIndex].Value !=null)
                    {
                        string fieldNameInDB =(string) dr.Cells[0].Value;
                        string fieldNameInFile = (string)dr.Cells[colIndex].Value;
                        if (!string.IsNullOrEmpty(fieldNameInDB) && !string.IsNullOrEmpty(fieldNameInFile))
                        {
                            PdfTableColumnHeaderMapping colMapping = new PdfTableColumnHeaderMapping();
                            colMapping.FieldNameInDB = fieldNameInDB;
                            colMapping.FieldNameInPdf = fieldNameInFile;
                            colMapping.FieldOrderInPdf = colMappings.Count;
                            colMappings.Add(colMapping);
                        }
                    }
                }
                if (colMappings.Count > 0)
                {
                    colOptions.Add(colIndex, colMappings);
                }
            }
            rule.ColHeaderOptions = colOptions;
            ExtractionRule.SaveRule(rule);
            return rule;
        }
        #endregion



    }
}
